﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;


namespace ConwaysGameOfLife
{
    public partial class GamePage : PhoneApplicationPage
    {
        UIElementRenderer elementRenderer;

        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

       private Vector2 _offset;

       private int _speedOfLife;

        bool LifeOn = false;

        private Grid _grid;

        Texture2D square;

        private int _heightOfScreen;
        private int _widthOfScreen;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;


            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            square = contentManager.Load<Texture2D>("block");
            //get the width and height of screen
          _heightOfScreen = SharedGraphicsDeviceManager.DefaultBackBufferHeight-100;
          _widthOfScreen = SharedGraphicsDeviceManager.DefaultBackBufferWidth + 20;
         
          _grid = new Grid(new Vector2(_widthOfScreen / square.Width, _heightOfScreen / square.Height));

          if (null == elementRenderer)
          {
              elementRenderer = new UIElementRenderer(this, (int)_widthOfScreen, (int)_heightOfScreen+100);
          }

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {


            // Stop the timer
            timer.Stop();
            
            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {

            TouchCollection touchCollection = TouchPanel.GetState();
            foreach (TouchLocation tl in touchCollection)
            {

                if (tl.State == TouchLocationState.Moved)
                {

                    _grid.SetStateOfCell((int)((tl.Position.X+20) / square.Width), (int)((tl.Position.Y+20) / square.Height), true);

                }

            }
            // TODO: Add your update logic here
            if (LifeOn)
            {
                _speedOfLife++;
                if (_speedOfLife > speed.Value)
                {
                    List<List<bool>> NewGrid = new List<List<bool>>();
                    for (int x = 0; x < _grid.GetWidth; x++)
                    {
                        NewGrid.Add(new List<bool>());
                        for (int y = 0; y < _grid.GetHeight; y++)
                        {
                            bool StateOfCell = _grid._GetStateOfCell(x, y);
                            int neighbors = 0;

                            if (_grid._GetStateOfCell(x - 1, y - 1))
                                neighbors++;
                            if (_grid._GetStateOfCell(x, y - 1))
                                neighbors++;
                            if (_grid._GetStateOfCell(x + 1, y - 1))
                                neighbors++;
                            if (_grid._GetStateOfCell(x - 1, y))
                                neighbors++;
                            if (_grid._GetStateOfCell(x + 1, y))
                                neighbors++;
                            if (_grid._GetStateOfCell(x - 1, y + 1))
                                neighbors++;
                            if (_grid._GetStateOfCell(x, y + 1))
                                neighbors++;
                            if (_grid._GetStateOfCell(x + 1, y + 1))
                                neighbors++;

                            if (!StateOfCell)
                            {
                                if (neighbors == 3)
                                {
                                    NewGrid[x].Add(true);
                                }
                                else
                                {
                                    NewGrid[x].Add(false);
                                }
                            }
                            else
                            {
                                if (neighbors <= 1)
                                {
                                    NewGrid[x].Add(false);
                                }
                                else if (neighbors >= 4)
                                {

                                    NewGrid[x].Add(false);
                                }
                                else
                                {
                                    NewGrid[x].Add(true);
                                }
                            }
                        }
                    }

                            _grid._GetGrid = NewGrid;
 
                    _speedOfLife = 0;
                }
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
          
            elementRenderer.Render();

            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.LightGray);
            spriteBatch.Begin();
            for (int x = 0; x < _grid.GetWidth; x++)
            {
                for (int y= 0;y < _grid.GetHeight; y++)
                {
                    if (_grid._GetStateOfCell(x, y))
                    {
                        spriteBatch.Draw(square, new Vector2((x-1) * square.Width, (y-1) * square.Height) + _offset, Color.White);
                    }
                }
            }
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();
            // TODO: Add your drawing code here
        }

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            if (Start.Content.ToString() == "Start")
            {
                Start.Content = "Stop";
                LifeOn = true;
                
            }
            else
            {
                Start.Content = "Start";
                LifeOn = false;
            }
        }

        private void Random_Click(object sender, RoutedEventArgs e)
        {
            _grid.RandomLife();
        }

        private void speed_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
           
        }

        
    }
}